<script setup lang="ts">
import type { StudentUnitItem, StudentUnitParams } from '@/api/types/student'
import type { UnitCategoryItem } from '@/pages/student/unitSelect/type'
import NavBar from '@/components/NavBar/index.vue'
import { CourseType } from '@/enums/course'
import { useCurrentStudentInfoStore } from '@/stores/modules/useCurrentStudentInfoStore'
import { useStudentUnitStore } from '@/stores/modules/useStudentUnitStore'
import { useUnitStudyWordsStore } from '@/stores/modules/useUnitStudyWordsStore'
import { message } from '@/utils/message'
import { navigateBack } from '@/utils/navigation'
import { isEmpty } from '@/utils/validate'
import { onLoad } from '@dcloudio/uni-app'
import { computed, ref } from 'vue'
import UnitSelectCard from './components/UnitSelectCard.vue'

// 常量提取
const INSPECT_ICON = 'inspect-icon'
const UNIT_NOT_FINISHED_MESSAGE = '单元还没有学完，请学完再进行单词检查'

const studentInfoStore = useCurrentStudentInfoStore()
const studentUnitStore = useStudentUnitStore()
const unitStudyWordsStore = useUnitStudyWordsStore()

const studentUnitParams = ref<StudentUnitParams>({
  studentId: studentInfoStore.studentId,
  lessonId: studentInfoStore.lessonId,
  courseId: 0,
})

const unitListData = studentUnitStore.unitListData

async function handleStudyItemTap(unitCategory: UnitCategoryItem, item: StudentUnitItem) {
  const params = {
    studentId: studentInfoStore.studentId,
    lessonId: studentInfoStore.lessonId,
    courseId: studentUnitParams.value.courseId,
    unitNo: item.unitNo,
  }

  if (unitCategory.icon === INSPECT_ICON) {
    if (isEmpty(item.shorthandNum)) {
      return message.info(UNIT_NOT_FINISHED_MESSAGE)
    }
    // 跳转学后检查
    unitStudyWordsStore.startStudyAfterCheck(params)
    return
  }

  unitStudyWordsStore.startPreCheckStudy(params)
}

const title = computed(() => {
  let name = unitListData.course.name
  if (unitListData.course.type === CourseType.EXPERIENCE) {
    name += '/体验课'
  }
  return name
})

function handleChangeUnit(item: StudentUnitItem) {
  console.log('切换单元')
  console.log(item)
  // 在这里处理切换单元的逻辑
}

onLoad((options) => {
  if (options && options.courseId) {
    studentUnitParams.value = {
      courseId: Number(options.courseId),
      studentId: studentInfoStore.studentId,
      lessonId: studentInfoStore.lessonId,
    }
    studentUnitStore.fetchUnitList(studentUnitParams.value)
  }
  else {
    console.error('courseId is required')
    // 处理 courseId 不存在的情况，例如显示错误信息或返回
  }
})
</script>

<template>
  <view class="unit-select">
    <NavBar :title="title" @left-click="navigateBack" />
    <UnitSelectCard
      v-for="(item, index) in unitListData.units"
      :key="index"
      class="unit-select-card"
      :unit-data="item"
      @change-unit="handleChangeUnit(item)"
      @study-item-tap="handleStudyItemTap($event, item)"
    />
  </view>
</template>

<style lang="scss" scoped>
.unit-select {
  padding: 20rpx 40rpx 40px;
  .unit-select-card {
    margin-bottom: 20rpx;
  }
}
</style>
